<template>
    <div>
        <Header />

        <div class="main-content">
            <p>
                <el-form :model="form" ref="form" label-width="150px">
                    <el-tabs type="border-card">
                        <el-tab-pane :label="$t('home.generalSetting')">
                            <template v-if="form.roomKeyType === 1">
                                <p>
                                    <el-alert :title="$t('home.useAuthCodeWarning')" type="warning" show-icon
                                        :closable="false"></el-alert>
                                </p>
                                <el-form-item :label="$t('home.room')" prop="roomId" :rules="[
                                    { required: true, message: $t('home.roomIdEmpty') },
                                    { type: 'integer', min: 1, message: $t('home.roomIdInteger') }
                                ]">
                                    <el-row>
                                        <el-col :span="6">
                                            <el-select v-model="form.roomKeyType" style="width: 100%">
                                                <el-option :label="$t('home.authCode')" :value="2"></el-option>
                                                <el-option :label="$t('home.roomId')" :value="1"></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="18">
                                            <el-input v-model.number="form.roomId" type="number" min="1"></el-input>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </template>

                            <el-form-item v-else-if="form.roomKeyType === 2" :label="$t('home.room')" prop="authCode"
                                :rules="[
                                    { required: true, message: $t('home.authCodeEmpty') },
                                    { pattern: /^[0-9A-Z]{12,14}$/, message: $t('home.authCodeFormatError') }
                                ]">
                                <el-row>
                                    <el-col :span="6">
                                        <el-select v-model="form.roomKeyType" style="width: 100%">
                                            <el-option :label="$t('home.authCode')" :value="2"></el-option>
                                            <el-option :label="$t('home.roomId')" :value="1"></el-option>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tooltip placement="top-start">
                                            <div slot="content">
                                                <!-- 不知道为什么router-link获取不到$router，还是用el-link了，不过会有一次丑陋的刷新 -->
                                                <el-link type="primary"
                                                    :href="$router.resolve({ name: 'help' }).href">{{
                                                        $t('home.howToGetAuthCode')
                                                    }}</el-link>
                                            </div>
                                            <el-input v-model.number="form.authCode"></el-input>
                                        </el-tooltip>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-card shadow="never">
                                <el-row :gutter="20">
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#AEETx"
                                                    target="_blank">
                                                    {{ $t('home.showDanmaku') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showDanmaku"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="4">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#AEETx"
                                                    target="_blank">
                                                    {{ $t('home.mergeSimilarDanmaku') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.mergeSimilarDanmaku"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="8">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#AEETx"
                                                    target="_blank">
                                                    {{ $t('home.maxNumber') }}
                                                </a>
                                            </span>
                                            <el-input v-model.number="form.maxNumber" type="number" min="1"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-card>
                            <el-card shadow="never">
                                <el-row :gutter="20">
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#z7YQT"
                                                    target="_blank">
                                                    {{ $t('home.showInteractWordEnter') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showInteractWordEnter"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#z7YQT"
                                                    target="_blank">
                                                    {{ $t('home.showInteractWordFollow') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showInteractWordFollow"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#z7YQT"
                                                    target="_blank">
                                                    {{ $t('home.showInteractWordShare') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showInteractWordShare"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-card>
                            <el-card shadow="never">
                                <el-row :gutter="20">
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#b9gux"
                                                    target="_blank">
                                                    {{ $t('home.showSuperchat') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showSuperchat"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#b9gux"
                                                    target="_blank">
                                                    {{ $t('home.showNewMember') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showNewMember"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#b9gux"
                                                    target="_blank">
                                                    {{ $t('home.showGift') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showGift"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item>
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#b9gux"
                                                    target="_blank">
                                                    {{ $t('home.showGiftInfo') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.showGiftInfo"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-card>
                            <el-card shadow="never">
                                <el-row :gutter="20">
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item :label="$t('home.danmakuAtBottom')">
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#BL6aV"
                                                    target="_blank">
                                                    {{ $t('home.danmakuAtBottom') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.danmakuAtBottom"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :xs="24" :sm="6">
                                        <el-form-item :label="$t('home.tickerAtButtom')">
                                            <span slot="label">
                                                <a href="https://www.yuque.com/doodle-irifi/ueaigm/laogg2#BL6aV"
                                                    target="_blank">
                                                    {{ $t('home.tickerAtButtom') }}
                                                </a>
                                            </span>
                                            <el-switch v-model="form.tickerAtButtom"></el-switch>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-card>
                        </el-tab-pane>


                    </el-tabs>
                </el-form>
            </p>

            <p style="max-width: 1250px; margin:10px auto;">
                <el-card class="login-card">
                    <el-alert :title="$t('home.useSecondaryScanCode')" type="warning"
                        style="background-color: #fef0f0; color: #F56C6C;" show-icon :closable="false"></el-alert>
                    <div class="login-card-content">
                        <el-tag :type="this.login.isLogin ? 'success' : 'danger'">{{ this.login.isLogin ?
                            $t('home.isLoginTrue') :
                            $t('home.isLoginFalse') }}</el-tag>
                        <div v-if="this.login.isLogin"> <el-tag>登录日期： {{ this.login.loginDate }}</el-tag></div>
                        <el-button type="primary" @click="startLogin">{{ $t('home.startLogin') }}</el-button>
                        <el-button v-if="this.login.isLogin" type="danger" @click="logout"
                            style="margin-left: 0;">{{ $t('home.logout') }}</el-button>
                        <img :src="this.login.image" style="max-width: 150px; max-height: 150px;"
                            v-if="this.login.image && this.login.image.length > 0" />
                    </div>
                </el-card>
            </p>

            <p style="max-width: 1250px; margin:10px auto;">
                <el-card>
                    <el-form :model="form" label-width="150px">
                        <p v-if="obsRoomUrl.length > 1024">
                            <el-alert :title="$t('home.urlTooLong')" type="warning" show-icon
                                :closable="false"></el-alert>
                        </p>
                        <el-tooltip :content="$t('home.roomUrlUpdated')" v-model="showRoomUrlUpdatedTip" manual
                            placement="top">
                            <el-form-item :label="$t('home.roomUrl')">
                                <el-input ref="roomUrlInput" readonly :value="obsRoomUrl"
                                    style="width: calc(100% - 8em); margin-right: 1em;"></el-input>
                                <el-button type="primary" icon="el-icon-copy-document" @click="copyUrl"></el-button>
                            </el-form-item>


                        </el-tooltip>
                        <el-tooltip :content="$t('home.roomUrlUpdated')" manual placement="top">
                            <el-form-item label="盲盒姬地址">
                                <el-input ref="giftUrlInput" readonly :value="giftUrl"
                                    style="width: calc(100% - 8em); margin-right: 1em;"></el-input>
                                <el-button type="primary" icon="el-icon-copy-document" @click="copyGiftUrl"></el-button>
                            </el-form-item>
                        </el-tooltip>

                        <el-tooltip :content="$t('home.roomUrlUpdated')" manual placement="top">
                            <el-form-item label="新版盲盒姬地址">
                                <el-input ref="giftUrlInput2" readonly :value="giftUrl2" style="width: calc(100% - 8em); margin-right: 1em;"></el-input>
                                <el-button type="primary" icon="el-icon-copy-document" @click="copyGiftUrl2"></el-button>
                            </el-form-item>
                        </el-tooltip>
                        <el-form-item>
                            <el-button type="primary" @click="openTutorial"
                                style="background: #bed742; border-color: #bed742;">{{
                                    $t('home.openTutorial') }}</el-button>
                            <el-button type="primary" @click="enterBilibili">{{ $t('home.enterBilibili') }}</el-button>
                            <el-button type="primary" :disabled="!roomUrl" @click="enterRoom">{{ $t('home.enterRoom')
                                }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </p>
        </div>

    </div>
</template>

<script>
import * as mainApi from '@/api/main'
import * as chatConfig from '@/api/chatConfig'
import Header from '@/components/Header.vue'
import axios from 'axios'
export default ({
    name: 'Index',
    components: {
        Header,
    },
    props: {
        user: {
            type: String,
            default: () => ({})
        }
    },
    data() {
        return {
            login: {
                image: '',
                isLogin: false,
                loginDate: ''
            },
            form: {
                ...chatConfig.getLocalConfig(),
                roomKeyType: parseInt(window.localStorage.roomKeyType || '2'),
                roomId: parseInt(window.localStorage.roomId || '1'),
                authCode: window.localStorage.authCode || '',
            },
            serverConfig: {
                enableUploadFile: false,
                loaderUrl: ''
            },
            // 因为$refs.form.validate是异步的所以不能直接用计算属性
            // getUnvalidatedRoomUrl -> unvalidatedRoomUrl -> updateRoomUrl -> roomUrl
            roomUrl: '',
            showRoomUrlUpdatedTip: false,
        }
    },
    created() {
        // console.log(this.user)
        // console.log(this.user === 'admin')

    },
    methods: {
        enterBilibili() {
            window.open(`https://live.bilibili.com/${this.form.roomId}`, '_blank')
        },
        openTutorial() {
            window.open(`https://www.yuque.com/doodle-irifi/ueaigm/laogg2`, '_blank')
        },
        enterRoom() {
            window.open(this.roomUrl, `room ${this.roomKeyValue}`, 'menubar=0,location=0,scrollbars=0,toolbar=0,width=600,height=600')
        },
        getUnvalidatedRoomUrl(isTestRoom) {
            // 重要的字段放在前面，因为如果被截断就连接不了房间了
            let frontFields = {
                roomKeyType: this.form.roomKeyType
            }
            let backFields = {
                lang: this.$i18n.locale,
                emoticons: this.useLocalEmoticonSetting ? JSON.stringify([]) : JSON.stringify(this.form.emoticons),
            }
            let ignoredNames = new Set(['roomId', 'authCode', 'customCss'])
            let query = { ...frontFields }
            for (let name in this.form) {
                if (!(name in frontFields || name in backFields || ignoredNames.has(name))) {
                    query[name] = this.form[name]
                }
            }
            Object.assign(query, backFields)

            // 去掉和默认值相同的字段，缩短URL长度
            query = Object.fromEntries(Object.entries(query).filter(
                ([name, value]) => {
                    let defaultValue = chatConfig.DEFAULT_CONFIG[name]
                    if (defaultValue === undefined) {
                        return true
                    }
                    if (typeof defaultValue === 'object') {
                        defaultValue = JSON.stringify(defaultValue)
                    }
                    return value !== defaultValue
                }
            ))
            let resolved
            if (isTestRoom) {
                resolved = this.$router.resolve({ name: 'test_room', query })
            } else {
                resolved = this.$router.resolve({ name: 'room', params: { roomKeyValue: this.roomKeyValue }, query })
            }
            return `${window.location.protocol}//${window.location.host}${resolved.href}`
        },
        copyUrl() {
            this.$refs.roomUrlInput.select()
            document.execCommand('Copy')
        },
        confirmCustomCSS() {
            window.localStorage.customCss = this.form.customCss
            chatConfig.setLocalConfig(this.form)
        },
        copyGiftUrl() {
            this.$refs.giftUrlInput.select()
            document.execCommand('Copy')
        },
        async updateRoomUrl() {
            // 防止切换roomKeyType时校验的还是老规则
            await this.$nextTick()
            try {
                await this.$refs.form.validate()
            } catch {
                this.roomUrl = ''
                return
            }
            // 没有异步的校验规则，应该不需要考虑竞争条件
            this.roomUrl = this.unvalidatedRoomUrl
        },
        delayHideRoomUrlUpdatedTip: _.debounce(function () {
            this.showRoomUrlUpdatedTip = false
        }, 3000),
        async updateServerConfig() {
            try {
                this.serverConfig = (await mainApi.getServerInfo()).config
            } catch (e) {
                this.$message.error(`Failed to fetch server information: ${e}`)
                throw e
            }
        },
        // 开始登录
        async startLogin() {
            const res = (await axios.get('/api/login/start')).data
            console.log(res)
            this.login.key = res.key
            this.login.image = `data:image/png;base64,${res.qr}`
            this.login.check = setInterval(this.checkLogin, 1000)
        },
        // 更新登录状态
        async updateLoginStatus() {
            const res = (await axios.get('/api/login/status')).data
            this.login.isLogin = res.is_login
            this.login.loginDate = res.login_date
            console.log(this.login.isLogin)
            if (res.success === false) {
                this.$message.error('登录已过期,正在刷新cookie,请稍等')
                this.refreshCookie()
                // 刷新成功后，设置定时器
                if (this.refreshFlag) {
                    window.setInterval(this.refreshCookie(), 1000 * 60 * 60 * 24 * 30)
                }
            }

        },
        // 退出登录
        async logout() {
            await axios.get('/api/login/kill')
            this.updateLoginStatus()
        },
        // 检查登录状态
        async checkLogin() {
            const res = (await axios.get('/api/login/check', { params: { 'qrcode_key': this.login.key } })).data
            if (res.ok === true) {
                this.login.image = ''
                clearInterval(this.login.check)
                this.updateLoginStatus()
            }
        },
        // 刷新cookie
        async refreshCookie() {
            const res = (await axios.get('/api/refresh/cookie')).data
            if (res.success === true) {
                this.refreshFlag = true
                this.$message.success('刷新成功')
                this.login.isLogin = res.is_login
                this.login.loginDate = res.login_date
            } else {
                this.refreshFlag = false
                this.$message.error('刷新失败,请重新扫码登录')
            }
        },

    },
    computed: {
        isAdmin() {
            return this.user && this.user === 'admin'
        },
        obsRoomUrl() {
            if (this.roomUrl === '') {
                return ''
            }
            if (this.serverConfig.loaderUrl === '') {
                return this.roomUrl
            }
            let url = new URL(this.serverConfig.loaderUrl)
            url.searchParams.append('url', this.roomUrl)
            return url.href
        },
        giftUrl() {
            let url = `${window.location.protocol}//${window.location.host}/gift/5389469`
            return url
        },
        roomKeyValue() {
            if (this.form.roomKeyType === 1) {
                return this.form.roomId
            } else {
                return this.form.authCode
            }
        },
        unvalidatedRoomUrl() {
            return this.getUnvalidatedRoomUrl(false)
        }
    },
    watch: {
        unvalidatedRoomUrl: 'updateRoomUrl',
        roomUrl: _.debounce(function (val, oldVal) {
            // 提示用户URL已更新
            // 如果语言不是默认的中文，则刷新页面时也会有一次提示，没办法
            if (val !== '' && oldVal !== '') {
                this.showRoomUrlUpdatedTip = true
                this.delayHideRoomUrlUpdatedTip()
            }

            // 保存配置
            window.localStorage.roomKeyType = this.form.roomKeyType
            window.localStorage.roomId = this.form.roomId
            window.localStorage.authCode = this.form.authCode
            // this.form.skinConfig = 'normal'
            chatConfig.setLocalConfig(this.form)
        }, 500)
    },
    mounted() {
        this.updateLoginStatus()
        this.updateRoomUrl()
        // this.updateServerConfig()
    }
})
</script>

<style scoped></style>